//https://leetcode.cn/problems/binary-search/
//⼆分查找
class Solution {
public:
    int search(vector<int>& nums, int target) 
    {
        int left = 0;
        int right = nums.size() - 1;
        while(left <= right)
        {
            int mid = (right + left) / 2;
            if(nums[mid] < target)
            {
                left = mid + 1;
            }
            else if(nums[mid] > target)
            {
                right = mid - 1;
            }
            else
            {
                return mid;
            }
        }
        return -1;
    }
};

//在排序数组中查找元素的第⼀个和最后⼀个位置
//https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
class Solution 
{
public:
    vector<int> searchRange(vector<int>& nums, int target) 
    {
        int left = 0;
        int right = nums.size() - 1;
        vector<int> ret;
        while(left <= right)
        {
            int mid = left + (right - left) / 2;
            if(nums[mid] < target)
            {
                left = mid + 1;
            }
            else if(nums[mid] > target)
            {
                right = mid - 1;
            }
            else
            {
                int i = mid;
                while(i >= 0 && nums[i] == target) i--;
                ret.push_back(i + 1);
                i = mid;
                while(i < nums.size()  && nums[i] == target) i++;
                ret.push_back(i - 1);
                return ret;
            }
        }
        vector<int> err = {-1,-1};
        return err;
    }
};

//x 的平⽅根
//https://leetcode.cn/problems/sqrtx/
class Solution {
public:
    int mySqrt(int x)
    {
        if( x < 1) return 0;
        int left = 1; 
        int right = x;
        while(left < right)
        {
            long long mid = left + (right - left + 1)/2;
            if( mid * mid <= x) left = mid;
            else right = mid - 1;
        }
        return left;
    }
};


//搜索插⼊位置
https://leetcode.cn/problems/search-insert-position/
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) 
    {
        int left = 0;
        int right = nums.size() - 1;

        while(left < right)
        {
            int mid = left + (right - left) / 2;

            if(nums[mid] < target) left = mid + 1;
            else right = mid;
        }

        if(nums[left] < target) return right + 1;

        return left;

    }
};